<?php

/**
 * 存储用户月经日历信息基类
 *
 * @author fuxiang <892576@gmail.com>
 *
 * $Id$
 */

namespace Tools;

use Common\Bridge;

class Emmenia
{
    /**
     * 表名
     */
    const EMMENIA_TABLE_NAME = 'Emmenia';
    const EMMENIA_SET_TABLE_NAME = 'EmmeniaSettings';

    /**
     * MC
     */

    const MCE_PFX = 'E_U:';
    const MCES_PFX = 'ES_U:';

    private function __construct()
    {
    }

    /**
     * 单条添加用户经期数据
     *
     * @param array $data 月经数据
     * @return mixed
     */
    public static function addEmmenia($data)
    {
        $uid = $data['UserId'];
        if ($uid < 1 || empty($data['RecordDate'])) {
            return false;
        }
        $newdata = [
            'UserId' => intval($data['UserId']),
            'RecordDate' => $data['RecordDate'],
            'RecordType' => empty($data['RecordType']) ? 1 : $data['RecordType'],
            'Period' => $data['Period'],
            'MonthPeriod' => empty($data['MonthPeriod']) ? '' : $data['MonthPeriod'],
            'UpdateTime' => empty($val['UpdateTime']) ? date('Y-m-d H:i:s') : $val['UpdateTime'],
            'CreateTime' => empty($val['CreateTime']) ? date('Y-m-d H:i:s') : $val['CreateTime'],
        ];
        $pdo = Bridge::pdo(Bridge::DB_ACT_W);
        $flag = $pdo->insert(self::EMMENIA_TABLE_NAME, $newdata, ['ignore' => true]);
        if ($flag !== false) {
            $mc = Bridge::memcache(Bridge::MEMCACHE_DEFAULT);
            $mc->delete(self::MCE_PFX . $uid);
            $id = $pdo->lastInsertId();
            return $id;
        }

        return false;
    }

    /**
     * 批条添加或是更新用户经期数据
     *
     * @param array $data 多条经期数据 （如果用户ID,记录日期,类型相同的数据则是更新）
     * @return mixed
     */
    public static function updateEmmenia($data)
    {
        if (!is_array($data)) {
            return false;
        }

        $newdata = $mckey = [];
        foreach ($data as $k => $val) {
            $newdata[$k] = [
                'UserId' => $val['UserId'],
                'RecordDate' => $val['RecordDate'],
                'RecordType' => empty($val['RecordType']) ? 1 : $val['RecordType'],
                'Period' => $val['Period'],
                'MonthPeriod' => empty($val['MonthPeriod']) ? '' : $val['MonthPeriod'],
                'UpdateTime' => empty($val['UpdateTime']) ? date('Y-m-d H:i:s') : $val['UpdateTime'],
                'CreateTime' => empty($val['CreateTime']) ? date('Y-m-d H:i:s') : $val['CreateTime']
            ];
            $mckey[$val['UserId']] = self::MCE_PFX . $val['UserId'];
        }

        $pdo = Bridge::pdo(Bridge::DB_ACT_W);
        $flag = $pdo->upsert(self::EMMENIA_TABLE_NAME, $newdata, ['Period', 'MonthPeriod', 'UpdateTime']);
        if ($flag !== false) {
            $mc = Bridge::memcache(Bridge::MEMCACHE_DEFAULT);
            $mc->delete($mckey);
            $id = $pdo->lastInsertId();
            return $id;
        }

        return false;
    }

    /**
     * 添加或更新经期设置数据
     *
     * @param array $data 月经数据
     * @return string 00:04:26
     */
    public static function addEmmeniaSet($data)
    {
        $uid = $data['UserId'];
        if ($uid < 1) {
            return false;
        }
        //取老数据
        $olddata = self::getEmmeniaSet($uid);
        $newdata = [
            'UserId' => intval($data['UserId']),
            'Period' => empty($data['Period']) ? 5 : $data['Period'],
            'MonthPeriod' => empty($data['MonthPeriod']) ? 28 : $data['MonthPeriod'],
            'LastDate' => empty($data['LastDate']) ? date('Y-m-d') : $data['LastDate']
        ];
        $pdo = Bridge::pdo(Bridge::DB_ACT_W);
        if ($olddata === false) {
            $flag = $pdo->insert(self::EMMENIA_SET_TABLE_NAME, $newdata, ['ignore' => true]);
        } else {
            $where = ['UserId' => $uid];
            $row = array_intersect_key($newdata, $olddata);
            unset($row['UserId']);
            $flag = $pdo->update(self::EMMENIA_SET_TABLE_NAME, $row, $where);
        }

        if ($flag !== false) {
            $mc = Bridge::memcache(Bridge::MEMCACHE_DEFAULT);
            $mc->delete(self::MCES_PFX . $uid);
            return true;
        }

        return null;
    }

    /**
     * 删除用户经期数据(单条)
     *
     * @param array $data 多条经期数据 （如果用户ID,记录日期,类型相同的数据则是更新）
     * @return mixed
     */
    public static function deleteEmmenia($data)
    {
        if (!is_array($data)) {
            return false;
        }

        $where = [
            'UserId' => $data['UserId'],
            'RecordDate' => $data['RecordDate'],
            'RecordType' => empty($data['RecordType']) ? 1 : $data['RecordType']
        ];
        $mckey = self::MCE_PFX . $data['UserId'];

        $pdo = Bridge::pdo(Bridge::DB_ACT_W);
        $flag = $pdo->delete(self::EMMENIA_TABLE_NAME, $where);
        if ($flag !== false) {
            $mc = Bridge::memcache(Bridge::MEMCACHE_DEFAULT);
            $mc->delete($mckey);
            $id = $pdo->lastInsertId();
            return $id;
        }

        return false;
    }


    /**
     * 获取经期设置数据
     *
     * @param integer $uid  用户ID
     * @return array  经期设置数据
     */
    public static function getEmmeniaSet($uid)
    {
        if ($uid < 1) {
            return false;
        }
        $mc = Bridge::memcache(Bridge::MEMCACHE_DEFAULT);
        $data = $mc->get(self::MCES_PFX . $uid);
        if (empty($data)) {
            $pdo_r = Bridge::pdo(Bridge::DB_ACT_R);
            $where = ['UserId' => $uid];
            $data =  $pdo_r->find(self::EMMENIA_SET_TABLE_NAME, $where, '*');
            $data = current($data);
            $mc->set(self::MCES_PFX . $uid, $data);
        }
        if (empty($data)) {
            return false;
        }

        return $data;
    }

    /**
     * 获取经期数据
     *
     * @param integer $uid     用户ID
     * @return array  经期数据
     */
    public static function getEmmenia($uid)
    {
        if ($uid < 1) {
            return ['total' => 0, 'data' => []];
        }

        $mc = Bridge::memcache(Bridge::MEMCACHE_DEFAULT);
        $data = $mc->get(self::MCE_PFX . $uid);
        if (empty($data)) {
            $pdo_r = Bridge::pdo(Bridge::DB_ACT_R);
            $where = ['UserId' => $uid];
            $order = 'RecordDate ASC,RecordType ASC';
            $data = $pdo_r->find(self::EMMENIA_TABLE_NAME, $where, '*', $order);
            $mc->set(self::MCE_PFX . $uid, $data);
        }
        if (empty($data)) {
            return ['total' => 0, 'data' => []];
        }
        $cnt = count($data);

        return ['total' => $cnt, 'data' => $data];
    }
}